package com.sky.controller.admin;


import com.sky.constant.JwtClaimsConstant;
import com.sky.context.BaseContext;
import com.sky.dto.AdminDTO;
import com.sky.dto.AdminLoginDTO;
import com.sky.entity.Admin;
import com.sky.properties.JwtProperties;
import com.sky.result.Result;
import com.sky.service.AdminService;
import com.sky.utils.JwtUtil;
import com.sky.vo.AdminLoginVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

import java.util.List;
import java.util.Map;
/**
 * @author LiZhiHan
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/admin/admin")
public class AdminController {

	private final AdminService adminService;

	private final JwtProperties jwtProperties;

	@PostMapping("login")
	public Result<AdminLoginVO> login(@RequestBody AdminLoginDTO adminLoginDTO) {
		log.info("管理端登录：{}", adminLoginDTO);

		// 登录校验
		Admin admin = adminService.login(adminLoginDTO);

		//登录成功后，生成jwt令牌
		Map<String, Object> claims = new HashMap<>();
		claims.put(JwtClaimsConstant.EMP_ID, admin.getId());
		String token = JwtUtil.createJWT(
				jwtProperties.getAdminSecretKey(),
				jwtProperties.getAdminTtl(),
				claims);
		//将登录者的id放到当前线程中
		BaseContext.setCurrentId(admin.getId());
		System.out.println();
		// 返回数据
		AdminLoginVO adminLoginVO =
				AdminLoginVO.builder()
						.id(admin.getId())
						.userName(admin.getUsername())
						.name(admin.getName())
						.token(token)
						.build();

		return Result.success(adminLoginVO);
	}

	@GetMapping("logout")
	public Result<String> logout() {
		log.info("管理端退出登录");
		BaseContext.removeCurrentId();
		return Result.success();
	}

	@PostMapping("add")
	public Result<String> add(@RequestBody AdminDTO adminDTO) {
		log.info("新增管理员：{}", adminDTO);
		adminService.add(adminDTO);
		return Result.success();
	}

	@PutMapping("update")
	public Result<String> update(@RequestBody AdminDTO adminDTO) {
		log.info("修改管理员：{}", adminDTO);
		adminService.update(adminDTO);
		return Result.success();
	}
	@DeleteMapping("/del")
	public Result del(@RequestBody AdminDTO adminDTO) {
		log.info("删除管理员{}", adminDTO);
		adminService.removeById(adminDTO.getId());
		return Result.success();
	}

}
